// 权限控制
import router from '@/router'
import { getToken } from './utils/auth'
// 引入进度条和进度条样式
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
// 引入store
import store from '@/store'

import { asyncRouter } from '@/router/asyncRouters'
// 设置白名单
const WHITE_LIST = ['/login', '/404']

// 路由前置守卫
router.beforeEach(async(to, from, next) => {
  // 获取本地token
  const token = getToken()
  // 进度条开始
  NProgress.start()
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      next()
      // 在这里调用actions最合适
      if (!store.state.user.userInfo.userId) {
        const res = await store.dispatch('user/getUserInfo')
        // console.log(res.roles.menus, asyncRouter)
        const menus = res.roles.menus
        const filterRooutes = asyncRouter.filter(route => menus.includes(route.children[0].name))
        // console.log(filterRooutes)
        router.addRoutes([...filterRooutes, { path: '*', redirect: '/404', hidden: true }])
        store.commit('menu/setMenuList', filterRooutes)
      }
    }
  } else {
    if (WHITE_LIST.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
  // 进度条结束
  NProgress.done()
})
